#include "point.h"
#include "3DAlgorithm/commonFunc/BasicTools/include/IOType/PointCloud.h"
namespace  ELEMENT {
    VertexCloud::VertexCloud():Element()
    {
        type = ElementType::Cloud;
    }

    void VertexCloud::setCloud(std::vector<Eigen::Vector3d> &cld, std::vector<int> ind)
    {
        assert(ind.empty() || ind.size() == cld.size());
        if(ind.empty()) {
            index.resize(cld.size());
            for(int i=0;i<index.size();++i) index[i]=i;
        }else {
            index = ind;
        }
        vertices = cld;
        for(int i=0;i<vertices.size();++i) {
            qDebug()<<vertices[i].x()<< vertices[i].y()<<vertices[i].z();
        }
        qDebug()<<index.size()<< vertices.size();

        QOpenGLVertexArrayObject::Binder bind(&VAO);
        qDebug()<<"vao point id: "<< VAO.objectId();
        qDebug()<< EBO.create();
        EBO.bind();
        EBO.allocate(index.data(), sizeof(GLint)*index.size());

        qDebug()<< VBO.create();       //生成VBO对象
        VBO.bind();         //将VBO绑定到当前的顶点缓冲对象（QOpenGLBuffer::VertexBuffer）中
        //将顶点数据分配到VBO中，第一个参数为数据指针，第二个参数为数据的字节长度
        VBO.allocate(vertices.data(), sizeof(Eigen::Vector3d)*vertices.size());
        glVertexAttribPointer(0, 3, GL_DOUBLE, GL_FALSE, sizeof(Eigen::Vector3d), (void*)0);
        glEnableVertexAttribArray(0);
    }

    void VertexCloud::setCloud(QString path)
    {
         std::vector<Eigen::Vector3d> cld;
         if(!PointCloud::readPoint(path.toStdString(), cld)) {
             qDebug()<< "read failed";
         }

         setCloud(cld);
    }

    void VertexCloud::Draw(QOpenGLShaderProgram &shader)
    {
        shader.bind();
        QOpenGLVertexArrayObject::Binder bind(&VAO);
        shader.setUniformValue("userColor",QVector4D(0.5f, 0.0f, 0.0f, 1.0f));
        // qDebug()<< "draw : "<< VAO.objectId()<<VAO.objectName();
        glDrawElements(GL_POINTS, index.size(), GL_UNSIGNED_INT, 0);
    }

    QString VertexCloud::Info()
    {
        QString info("类型：点云\n数量：%1");
        return info.arg(vertices.size());
    }
}
